package com.example.login;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeoutException;

import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener{

	EditText ed1, ed2;
	Button bt;
	private static int login = 0;
	private static Context context;
	TransparentProgressDialog pd;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		context = this;
		ed1 = (EditText) findViewById(R.id.editText1);
		ed2 = (EditText) findViewById(R.id.editText2);
		bt = (Button) findViewById(R.id.button1);
		bt.setOnClickListener(this);
		TextView tv = (TextView) findViewById(R.id.textView1);
		tv.setOnClickListener(this);
		
		pd = new TransparentProgressDialog(this, R.drawable.loading);
		
	}
	
	public static String md5(final String s) {
	    final String MD5 = "MD5";
	    try {
	        // Create MD5 Hash
	        MessageDigest digest = java.security.MessageDigest
	                .getInstance(MD5);
	        digest.update(s.getBytes());
	        byte messageDigest[] = digest.digest();

	        // Create Hex String
	        StringBuilder hexString = new StringBuilder();
	        for (byte aMessageDigest : messageDigest) {
	            String h = Integer.toHexString(0xFF & aMessageDigest);
	            while (h.length() < 2)
	                h = "0" + h;
	            hexString.append(h);
	        }
	        return hexString.toString();

	    } catch (NoSuchAlgorithmException e) {
	        e.printStackTrace();
	    }
	    return "";
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.button1:
			String s1 = ed1.getText().toString().trim();
			String s2 = md5(ed2.getText().toString().trim());
			System.out.println("username : "+s1);
			System.out.println("Password : "+s2);
//			if(s1.length() < 6 || s2.length() < 6)
//			{
//				Toast.makeText(this, "Tài khoản hoặc mật khẩu quá ngắn.", Toast.LENGTH_LONG).show();
//			} else {
				new BG().execute(s1, s2);
//			}
			break;
		case R.id.textView1:
			Toast.makeText(this, "textview touch.", Toast.LENGTH_LONG).show();
			break;
		default:
			break;
		}
		
	}
	class BG extends AsyncTask<String, Void, Void>
	{

	
		
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			pd.setTitle("Login");
			pd.show();
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if(login == 1)
			{
				Toast.makeText(context, "Success", Toast.LENGTH_LONG).show();
			}else {
				Toast.makeText(context, "Fail", Toast.LENGTH_LONG).show();
			}
			final Handler handler = new Handler();
			handler.postDelayed(new Runnable() {
			    @Override
			    public void run() {
			    	pd.dismiss();
			    }
			}, 30000L);
			
		}

		

		@Override
		protected Void doInBackground(String... params) {
			// TODO Auto-generated method stub
			try{
				System.out.println("Link : "+"http://tvhieuit.twomini.com/test/login.php?a="+params[0].toString().trim()+"&b="+params[1].toString().trim());
				URL url = new URL("http://tvhieuit.twomini.com/test/login.php?a="+params[0].toString().trim()+"&b="+params[1].toString().trim());
	            URLConnection conn = url.openConnection();
	            conn.setReadTimeout(2*60*1000);// set timeout 2 minute
	            // Get the response
	            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
	            String line = "";
	            String s = "";
	            while ((line = rd.readLine()) != null) {
	            	
	            	s += line;
	            }
	            System.out.println("s = "+s);
	            login = Integer.parseInt(s);
			}
			catch(Exception e)
			{
				login = 0;
				e.printStackTrace();				
			}
			return null;
		}
		
	}
	
	private class TransparentProgressDialog extends Dialog {
		
		private ImageView iv;
			
		public TransparentProgressDialog(Context context, int resourceIdOfImage) {
			super(context, R.style.MyTheme);
	        	WindowManager.LayoutParams wlmp = getWindow().getAttributes();
	        	wlmp.gravity = Gravity.CENTER_HORIZONTAL;
	        	getWindow().setAttributes(wlmp);
			setTitle(null);
			setCancelable(false);
			setOnCancelListener(null);
			LinearLayout layout = new LinearLayout(context);
			layout.setOrientation(LinearLayout.VERTICAL);
			LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
			iv = new ImageView(context);
			iv.setImageResource(resourceIdOfImage);
			iv.setScaleType(ScaleType.FIT_XY);
			layout.addView(iv, params);
			addContentView(layout, params);
		}
			
		@Override
		public void show() {
			super.show();
			RotateAnimation anim = new RotateAnimation(0.0f, 360.0f , Animation.RELATIVE_TO_SELF, .5f, Animation.RELATIVE_TO_SELF, .5f);
			anim.setInterpolator(new LinearInterpolator());
			anim.setRepeatCount(Animation.INFINITE);
			anim.setDuration(300);
			iv.setAnimation(anim);
			iv.startAnimation(anim);
		}
	}
}
